package dahlpay

import (
    "fmt"
	"time"
	"errors"
	"strconv"
	"crypto/md5"
	"thirdpaysdk/core"
	"github.com/astaxie/beego"
)

type RefundReq struct { 
	Chid    string  `json:"chid"`    //渠道编码      
	Reqexts string  `json:"reqexts"` //合作方唯一流水号
	Payno   string  `json:"payno"`   //我方提供的流水号
	Amount  string  `json:"amount"`  //退款金额
	Timeamp string  `json:"timeamp"` //时间戳(年年年年月月日日时时分分秒秒)
	Sign    string  `json:"sign"`    //数字签名
}

type RefundsResponse struct {
	ErrCode       string  `json:"errcode,omitempty"`
	ErrMsg        string  `json:"errmsg,omitempty"`
}

func makeRefundMd5Sign(amount,chid,payno,timeamp,appSecret string) string {
	str := fmt.Sprintf("amount=%s&chid=%s&payno=%s&timeamp=%s%s",amount,chid,payno,timeamp,appSecret)
	return fmt.Sprintf("%X", md5.Sum([]byte(str)))
}

func  Refunds(mchId,appSecret,orderId,outerId string,amount float32) (RefundsResponse, error){
	incompleteURL := "http://alid.dahl.ltd/paycenter/reb?amount=%s&chid=%s&payno=%s&timeamp=%s&sign=%s"
	curTime := time.Now().Format("20060102150405")
	amountStr :=  strconv.FormatFloat(float64(amount), 'f', -1, 32)
	sign := makeRefundMd5Sign(amountStr,mchId,outerId,curTime,appSecret)
	serverUrl := fmt.Sprintf(incompleteURL,amountStr,mchId,outerId,curTime,sign)
	beego.Debug("Refunds serverUrl:", serverUrl)
	var rsp RefundsResponse
	client := core.GetPayJSONClient("GET", serverUrl)
	_, err := client.PayJsonExcute(nil, &rsp)
    if err != nil {
		return rsp, err
	}
	if rsp.ErrCode != "1000" {
	    message := rsp.ErrCode + ":" + rsp.ErrMsg
		return rsp, errors.New(message)
	}
	return rsp, nil
}
